import config from "../common/config";
import store from "/store/index.js";
import {
	ref,
	nextTick
} from "vue";

function generateUniqueValue() {
	return Date.now().toString();
}

let taskList = [];
let isRedirecting = false; // 防止重复跳转
const request = (url = "", date = {}, type = "GET") => {
	return new Promise((resolve, reject) => {
		const requestTask = uni.request({
			url: config.baseUrl + url,
			method: type,
			data: {
				// userId: store.state.userInfo.id,
				...date,
			},
			header: {
				Authorization: store.state.token || "",
			},
			dataType: "json",
			success: (res) => {
				const code = res.data.code;

				if (code === 401 && !isRedirecting) {
					isRedirecting = true;
					// 跳转到登录页面
					uni.showModal({
						title: '提示',
						content: '登录失效，请重新登录',
						showCancel: false,
						success: function(res) {
							if (res.confirm) {
								uni.reLaunch({
									url: '/pages/login/login',
									complete: () => {
										// 确保跳转完成后重置标志
										isRedirecting = false;
									}
								});
							} else if (res.cancel) {
								isRedirecting = false;
								console.log('用户点击取消');
							}
						}
					});
					// 拒绝所有后续处理
					reject(res);
				} else if (code !== 401) {
					// 正常响应
					resolve(res.data);
				} else {
					// 已经是401但已经在跳转中，直接拒绝
					reject(res);
				}
			},
			fail: (error) => {
				console.log(error, "failed");
				uni.hideLoading();
				reject(error);
			},
			complete: () => {
				uni.hideLoading();
				taskList = taskList.filter((i) => i.taskId !== taskId);
			},
		});
		const taskId = generateUniqueValue() + requestTask.uniqueId;
		taskList.push({
			taskId,
			requestTask,
		});
	});
};
export const get = (url, data) => {
	return request(url, data);
};

export const post = (url, data) => {
	return request(url, data, "POST");
};
export const put = (url, data) => {
	return request(url, data, "put");
};